package com.example.usermanagement.Interceptor;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.usermanagement.context.UserContext;
import com.example.usermanagement.enums.ResponseStatus;
import com.example.usermanagement.liuka.model.SysUser;
import com.example.usermanagement.vo.ResultVO;
import com.example.usermanagement.vo.UserInfoVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author yha
 * @ClassName
 * @description:TODO
 * @date 2024年09月10日
 * @version: 1.0.0
 */
public class AuthInterceptor implements HandlerInterceptor {


    private static final String  TOKEN = "token";
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("TOKEN");
        if(StrUtil.isBlank(token)){
            ResultVO resultVO = new ResultVO();
            resultVO.setCode(ResponseStatus.AUTH_ERROR_TOKEN.getCode());
            resultVO.setMsg(ResponseStatus.AUTH_ERROR_TOKEN.getMsg());
            response.getWriter().println(JSONObject.toJSONString(resultVO));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=UTF-8");
            return false;
        }
         try {
            String model =  Base64.decodeStr(token);
             UserInfoVO user = JSONObject.parseObject(model,UserInfoVO.class);
             UserContext.setUserInfoVOThreadLocal(user);
         }catch (Exception e){
             ResultVO resultVO = new ResultVO();
             resultVO.setCode(ResponseStatus.AUTH_ERROR_TOKEN.getCode());
             resultVO.setMsg(ResponseStatus.AUTH_ERROR_TOKEN.getMsg());
             response.getWriter().println(JSONObject.toJSONString(resultVO));
             response.setCharacterEncoding("UTF-8");
             response.setContentType("application/json; charset=UTF-8");
             return false;
         }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
